/**
 * @FilePath     : log_view_model.h
 * @Description  : 日志视图模型 - 提供日志展示、过滤和管理功能
 */
#pragma once

#include "base_view_model.h"
#include "kernel/dtos/log_entry_dto.h"
#include <QAbstractListModel>
#include <QSortFilterProxyModel>
#include <QDateTime>
#include <QVector>
#include <QRecursiveMutex>
#include <memory>

namespace presentation::viewmodels {

/**
 * @brief 系统日志列表模型
 * @details 为 QML ListView 提供日志数据，支持大量日志的高效管理
 */
class SystemLogModel : public QAbstractListModel {
    Q_OBJECT
    Q_PROPERTY(int count READ count NOTIFY countChanged)
    Q_PROPERTY(int infoCount READ infoCount NOTIFY statsChanged)
    Q_PROPERTY(int warnCount READ warnCount NOTIFY statsChanged)
    Q_PROPERTY(int errorCount READ errorCount NOTIFY statsChanged)

public:
    /**
     * @brief 日志数据角色枚举
     */
    enum LogRoles {
        TimestampRole = Qt::UserRole + 1,
        TimeStringRole,
        LevelRole,
        SourceRole,
        MessageRole,
        FullDateTimeRole
    };
    Q_ENUM(LogRoles)

    /**
     * @brief 内部日志条目结构
     */
    struct LogEntry {
        QDateTime timestamp;
        QString level;
        QString source;
        QString message;
    };

    explicit SystemLogModel(QObject* parent = nullptr);
    ~SystemLogModel() override = default;

    // QAbstractListModel 接口实现
    int rowCount(const QModelIndex& parent = QModelIndex()) const override;
    QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
    QHash<int, QByteArray> roleNames() const override;

    // 属性访问器
    int count() const { return static_cast<int>(m_entries.size()); }
    int infoCount() const { return m_infoCount; }
    int warnCount() const { return m_warnCount; }
    int errorCount() const { return m_errorCount; }

    /**
     * @brief 添加日志条目
     */
    Q_INVOKABLE void addEntry(const QDateTime& timestamp, const QString& level,
                               const QString& source, const QString& message);

    /**
     * @brief 清空所有日志
     */
    Q_INVOKABLE void clear();

    /**
     * @brief 导出日志为 QVariantList
     */
    Q_INVOKABLE QVariantList exportLogs() const;

    /**
     * @brief 设置最大日志条目数
     */
    void setMaxEntries(int max) { m_maxEntries = max; }

    /**
     * @brief 获取最大日志条目数
     */
    int maxEntries() const { return m_maxEntries; }

signals:
    void countChanged();
    void statsChanged();
    void entryAdded();

private:
    QVector<LogEntry> m_entries;
    int m_maxEntries{1000};
    int m_infoCount{0};
    int m_warnCount{0};
    int m_errorCount{0};
    mutable QRecursiveMutex m_mutex;

    void updateStats(const QString& level, int delta);
    void trimOldEntries();
};

/**
 * @brief 日志级别过滤代理模型
 */
class LogFilterProxyModel : public QSortFilterProxyModel {
    Q_OBJECT
    Q_PROPERTY(QString levelFilter READ levelFilter WRITE setLevelFilter NOTIFY levelFilterChanged)

public:
    explicit LogFilterProxyModel(QObject* parent = nullptr);

    QString levelFilter() const { return m_levelFilter; }
    void setLevelFilter(const QString& filter);

signals:
    void levelFilterChanged();

protected:
    bool filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const override;

private:
    QString m_levelFilter{"all"};
};

/**
 * @brief 日志视图模型
 * @details 提供日志过滤、自动滚动、导出等功能
 */
class LogViewModel : public BaseViewModel {
    Q_OBJECT

    Q_PROPERTY(SystemLogModel* logModel READ logModel CONSTANT)
    Q_PROPERTY(LogFilterProxyModel* filteredModel READ filteredModel CONSTANT)
    Q_PROPERTY(QString levelFilter READ levelFilter WRITE setLevelFilter NOTIFY levelFilterChanged)
    Q_PROPERTY(bool autoScroll READ autoScroll WRITE setAutoScroll NOTIFY autoScrollChanged)
    Q_PROPERTY(int totalCount READ totalCount NOTIFY statsChanged)
    Q_PROPERTY(int infoCount READ infoCount NOTIFY statsChanged)
    Q_PROPERTY(int warnCount READ warnCount NOTIFY statsChanged)
    Q_PROPERTY(int errorCount READ errorCount NOTIFY statsChanged)

public:
    explicit LogViewModel(QObject* parent = nullptr);
    ~LogViewModel() override;

    // 重写 BaseViewModel
    void initialize() override;
    void cleanup() override;

    // 属性访问器
    SystemLogModel* logModel() const { return m_logModel.get(); }
    LogFilterProxyModel* filteredModel() const { return m_filteredModel.get(); }

    QString levelFilter() const { return m_levelFilter; }
    void setLevelFilter(const QString& filter);

    bool autoScroll() const { return m_autoScroll; }
    void setAutoScroll(bool enabled);

    int totalCount() const;
    int infoCount() const;
    int warnCount() const;
    int errorCount() const;

    // QML 可调用方法
    Q_INVOKABLE void clearLogs();
    Q_INVOKABLE void exportToFile(const QString& filePath);
    Q_INVOKABLE void setMaxEntries(int max);

    /**
     * @brief 添加测试日志（用于开发调试）
     */
    Q_INVOKABLE void addTestLog(const QString& level, const QString& message);

signals:
    void levelFilterChanged();
    void autoScrollChanged();
    void statsChanged();
    void scrollToBottom();

private slots:
    void onLogReceived(const QDateTime& timestamp, const QString& level,
                       const QString& source, const QString& message);
    void onEntryAdded();

private:
    std::unique_ptr<SystemLogModel> m_logModel;
    std::unique_ptr<LogFilterProxyModel> m_filteredModel;
    QString m_levelFilter{"all"};
    bool m_autoScroll{true};

    void connectToLogBroadcast();
};

} // namespace presentation::viewmodels
